package com.njym.java.security.app.rest;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.njym.java.security.app.biz.*;
import com.njym.java.security.app.entity.*;
import com.njym.java.security.app.utils.RedisUtils;
import com.njym.java.security.common.msg.ObjectRestResponse;
import com.njym.java.security.common.msg.TableResultResponse;
import com.njym.java.security.common.rest.BaseController;
import com.njym.java.security.common.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Controller
@RequestMapping("/courseCatalogue")
public class CourseCatalogueController extends BaseController<CourseCatalogueBiz, CourseCatalogue> {
	@Autowired
	private FamilySlideshowBiz familySlideshowBiz;

	@Autowired
	private CourseClassifyBiz courseClassifyBiz;

	@Autowired
	private CourseSectionBiz courseSectionBiz;

	@Autowired
	private LikeOrCollectBiz likeOrCollectBiz;

	@Autowired
	private RedisUtils redisUtil;
	@RequestMapping(value = "/getSectionInfo", method = RequestMethod.GET)
	@ResponseBody
	public ObjectRestResponse<Object> getSectionInfo(
		@RequestParam(defaultValue = "10") int limit, @RequestParam(defaultValue = "1") int page, String couId) {
		if (!couId.equals("undefined")) {
			return new ObjectRestResponse<>().rel(true).data(baseBiz.getSetionInfo(couId,page,limit));
		} else {    //如果参数为undefind
			return new ObjectRestResponse<>().rel(false);
		}
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public TableResultResponse<Object> lists(@RequestParam(defaultValue = "10") int limit, @RequestParam(defaultValue = "1") int page, String token) {
		Example example = new Example(CourseCatalogue.class);
		Page<Object> result = PageHelper.startPage(page, limit);
		baseBiz.selectByExample(example);
		return new TableResultResponse<>(result.getPages(), result.getResult());
	}

	@RequestMapping(value = "/queryList", method = RequestMethod.GET)
	@ResponseBody
	public Object queryList(
		@RequestParam(defaultValue = "10") int limit, @RequestParam(defaultValue = "1") int page, String userId) {
		if (!userId.equals("undefined")) {
			List<CourseCatalogue> list = baseBiz.getCourse(page, limit, Integer.parseInt(userId));
			long total = PageInfo.of(list).getTotal();
			int totalPages = (int)Math.ceil((double)total / limit);
			return new TableResultResponse<>(totalPages, list);
		} else {
			return ResponseUtil.fail(40301, "错误！");
		}
	}

	/**
	 * 获取APP新首页的基础数据
	 *
	 * @return
	 */
	@RequestMapping(value = "/getIndexInfo", method = RequestMethod.GET)
	@ResponseBody
	public ObjectRestResponse<Object> getIndexInfo() {
		Map<String, Object> data = new HashMap<>();
		List<FamilySlideshow> slides = familySlideshowBiz.getSlide("首页");        //获取首页轮播图
		data.put("slides", slides);
		List<CourseSectionVo> sectionFree = courseSectionBiz.get_5_freeSections();
		//12.29改为获取免费课时,sql限制5条，倒序获得最新的

		sectionFree.forEach(CourseSectionVo ->{
			// 获取每一篇文章在redis中的浏览量，存入到数据库中
			String key  = "id_"+CourseSectionVo.getId();
			Long view = redisUtil.size(key);
			if(view>0){
				Long views = view + CourseSectionVo.getPlayTimes();
				CourseSectionVo.setPlayTimes(Math.toIntExact(views));
//				sectionFree[].add(CourseSectionVo);
			}
		});


		data.put("sectionFree", sectionFree);
		//		List<CourseCatalogueVo> courses = courseCatalogueBiz.getCourses();			//12.29修改为首页也放课时，所以暂时注释掉
		List<CourseClassify> classfies = courseClassifyBiz.get_2to5_classes();        //id是2到5的分类，即家庭、职场、名师、爱能
		classfies.forEach(classfy -> {
			List<CourseSection> list = courseSectionBiz.get_2_FreeSections_ByclassId(classfy.getId());
			list.forEach(CourseSection ->{
				// 获取每一篇文章在redis中的浏览量，存入到数据库中
				String key  = "id_"+CourseSection.getId();
				Long view = redisUtil.size(key);
				if(view>0){
					Long views = view + CourseSection.getPlayTimes();
					CourseSection.setPlayTimes(Math.toIntExact(views));
//					list.add(CourseSection);
				}
			});

			data.put(classfy.getName(), list);
		});

		return new ObjectRestResponse<>().rel(true).data(data);
	}

	@RequestMapping(value = "/getOne", method = RequestMethod.GET)
	@ResponseBody
	public Object getOne(String couId) {
		if (!couId.equals("undefined")) {
			CourseCatalogue courseCatalogue = baseBiz.selectById(Integer.parseInt(couId));
			Map<String, Object> map = new HashMap<>(2);
			map.put("data", courseCatalogue);
			return new ObjectRestResponse<>().rel(true).data(map);
		} else {    //如果参数为undefind
			return ResponseUtil.fail(40301, "错误！");
		}
	}

	/**
	 * 获取爱能人生分页数据
	 *
	 * @return
	 */
	@RequestMapping(value = "/getAineng_Life", method = RequestMethod.GET)
	@ResponseBody
	public ObjectRestResponse<Object> getAineng_Life(String classifyName) {
		Map<String, Object> data = new HashMap<>();
		//免费的课程，最新的2个
		List<CourseCatalogue> freeCourses = baseBiz.getAinengLife_free(classifyName);
		//其他课程，又∞变了，成了365课程和520课程？
		List<CourseCatalogue> otherCourses = baseBiz.getAinengLife_others(classifyName);
		data.put("freeCourses", freeCourses);
		data.put("otherCourses", otherCourses);
		return new ObjectRestResponse<>().rel(true).data(data);
	}

	/**
	 * 获取家庭教育分页数据
	 *
	 * @return
	 */
	@RequestMapping(value = "/getFamily_edu", method = RequestMethod.GET)
	@ResponseBody
	public ObjectRestResponse<Object> getFamily_edu(String classifyName) {
		Map<String, Object> data = new HashMap<>();
		//免费的课程，最新的5个
		List<CourseCatalogue> freeCourses = baseBiz.getFamilyEdu_free(classifyName);
		//讲师专栏，最新的2个
		List<CourseCatalogue> otherCourses = baseBiz.getFamilyEdu_others(classifyName);
		//早教万花筒
		CourseCatalogue entity = new CourseCatalogue();
		entity.setCourseName("早教万花筒");
		CourseCatalogue babyEdu = baseBiz.selectOne(entity);
		data.put("freeCourses", freeCourses);
		data.put("otherCourses", otherCourses);
		data.put("babyEdu", babyEdu);
		return new ObjectRestResponse<>().rel(true).data(data);
	}

	/**
	 * 12.29首页修改，根据分类id查询各分类的课时，按照课程进行分类
	 *
	 * @return
	 */
	@RequestMapping(value = "/getInfo_byClassId", method = RequestMethod.GET)
	@ResponseBody
	public Object getInfo_byClassId(String classId) {
		if (!classId.equals("undefined")) {        //参数不为undefined
			Map<String, Object> data = new HashMap<>();
			//免费的课时，最新的5个
			List<CourseSection> freeCourses = courseSectionBiz.get_freeSections(Integer.parseInt(classId));
			freeCourses.forEach(CourseSection ->{
				// 获取每一篇文章在redis中的浏览量，存入到数据库中
				String key  = "id_"+CourseSection.getId();
				Long view = redisUtil.size(key);
				if(view>0){
					Long views = view + CourseSection.getPlayTimes();
					CourseSection.setPlayTimes(Math.toIntExact(views));
				}
			});

			//查找该分类下的课程
			Example example = new Example(CourseCatalogue.class);
			example.createCriteria().andEqualTo("attr1", Integer.parseInt(classId));
			example.orderBy("orders").desc();
			List<CourseCatalogue> courses = baseBiz.selectByExample(example);
			//每个课程下的课时都查2个，并根据课程名分类
			List<Object> list = new ArrayList<>();
			courses.forEach(item -> {
				Map<String, Object> map = new HashMap<>();
				map.put("name", item.getCourseName());
				map.put("couId", item.getId());

				List<CourseSection> lists = 	courseSectionBiz.get_sectionsByCouid(item.getId());
				lists.forEach(CourseSection ->{
					// 获取每一篇文章在redis中的浏览量，存入到数据库中
					String key  = "id_"+CourseSection.getId();
					Long view = redisUtil.size(key);
					if(view>0){
						Long views = view + CourseSection.getPlayTimes();
						CourseSection.setPlayTimes(Math.toIntExact(views));
					}
				});
				map.put("list", lists);
				list.add(map);
			});
			data.put("freeCourses", freeCourses);
			data.put("theMap", list);

			Example slideExample = new Example(FamilySlideshow.class);
			Example sectionExample = new Example(CourseSection.class);
			Example courseExample = new Example(CourseCatalogue.class);
			if (Integer.parseInt(classId) == 2) {   //如果分类id是2，即点击了家庭教育，则家庭教育的轮播图//1.15轮播图改为课时推荐
                courseExample.createCriteria().andEqualTo("attr1",2);
//			List<FamilySlideshow> familyEdu_slides = familySlideshowBiz.selectByExample(slideExample);
				List<CourseCatalogue> familyEdu_courses = baseBiz.selectByExample(courseExample);
				List<Integer> ids = new ArrayList<>();
				familyEdu_courses.forEach( item -> {
					ids.add(item.getId());
				});
				sectionExample.createCriteria().andEqualTo("recommend",1).andIn("couId",ids);
				List<CourseSection> familyEdu_slides = courseSectionBiz.selectByExample(sectionExample);
				familyEdu_slides.forEach(CourseSection ->{
					// 获取每一篇文章在redis中的浏览量，存入到数据库中
					String key  = "id_"+CourseSection.getId();
					Long view = redisUtil.size(key);
					if(view>0){
						Long views = view + CourseSection.getPlayTimes();
						CourseSection.setPlayTimes(Math.toIntExact(views));
					}
				});
				data.put("familyEdu_courses",familyEdu_courses);
				data.put("familyEdu_slides", familyEdu_slides);
            }
			if (Integer.parseInt(classId) == 3) {   //如果分类id是3，即点击了职场智库
				slideExample.createCriteria().andEqualTo("status",1).andEqualTo("deleted",0).andEqualTo("name","职场智库");
				courseExample.createCriteria().andEqualTo("attr1",3);
				sectionExample.createCriteria().andEqualTo("recommend",1);
//				List<CourseSection> familyEdu_slides = courseSectionBiz.selectByExample(sectionExample);
				List<FamilySlideshow> familyEdu_slides = familySlideshowBiz.selectByExample(slideExample);
				List<CourseCatalogue> familyEdu_courses = baseBiz.selectByExample(courseExample);
				data.put("familyEdu_courses",familyEdu_courses);
				data.put("familyEdu_slides", familyEdu_slides);
			}
			if (Integer.parseInt(classId) == 7) {   //如果分类id是7，即点击了520
				slideExample.createCriteria().andEqualTo("status",1).andEqualTo("deleted",0).andEqualTo("name","520系列");
				courseExample.createCriteria().andEqualTo("attr1",7);
				sectionExample.createCriteria().andEqualTo("recommend",1);
//				List<CourseSection> familyEdu_slides = courseSectionBiz.selectByExample(sectionExample);
				List<FamilySlideshow> familyEdu_slides = familySlideshowBiz.selectByExample(slideExample);
				List<CourseCatalogue> familyEdu_courses = baseBiz.selectByExample(courseExample);
				data.put("familyEdu_courses",familyEdu_courses);
				data.put("familyEdu_slides", familyEdu_slides);
			}
//			List<CourseSection> familyEdu_slides = courseSectionBiz.selectByExample(sectionExample);
////			List<FamilySlideshow> familyEdu_slides = familySlideshowBiz.selectByExample(slideExample);
//			List<CourseCatalogue> familyEdu_courses = baseBiz.selectByExample(courseExample);
//			data.put("familyEdu_courses",familyEdu_courses);
//			data.put("familyEdu_slides", familyEdu_slides);

			return new ObjectRestResponse<>().rel(true).data(data);
		} else {    //如果参数为undefind
			return ResponseUtil.fail(40301, "错误！");
		}
	}

	/**
	 * 获取所有课程分类
	 *
	 * @return
	 */
	@RequestMapping(value = "/getCourseClassifies", method = RequestMethod.GET)
	@ResponseBody
	public ObjectRestResponse<Object> getCourseClassifies() {
		CourseClassify entity = new CourseClassify();
		entity.setDeleted(0);
		List<CourseClassify> classifies = courseClassifyBiz.selectList(entity);        //获得课程分类
		List<CourseCatalogueVo> classCounts = baseBiz.getClassCount();        //每个分类的总页数
		//		List<CourseCatalogue> list = baseBiz.getTenCourses();		//每个分类都获取10条最近的课程数据
		List<CourseCatalogueVo> list = baseBiz.getTenCourse();    //获取第一个分类的10条最新数据
		Map<String, Object> data = new HashMap<>(3);
		data.put("classifies", classifies);
		data.put("list", list);
		data.put("classCounts", classCounts);
		return new ObjectRestResponse<>().rel(true).data(data);
	}

	/**
	 * 获取爱能人生-导师课程-张晋老师专业课程页面初始数据
	 *
	 * @return
	 */
	@RequestMapping(value = "/getZhangJin_recommend", method = RequestMethod.GET)
	@ResponseBody
	public ObjectRestResponse<Object> getZhangJin_recommend() {
		List<CourseCatalogue> list = baseBiz.getZhangJin_recommend();
		List courses_365 = new ArrayList();
		List courses_520 = new ArrayList();
		list.forEach(course -> {
			if (course.getAttr1() == 6) {
				courses_365.add(course);
			} else {
				courses_520.add(course);
			}
		});
		Map<String, Object> data = new HashMap<>(3);
		data.put("courses_365", courses_365);
		data.put("courses_520", courses_520);
		return new ObjectRestResponse<>().rel(true).data(data);
	}

	/**
	 * 根据课程分类id获取分类课程
	 *
	 * @return
	 */
	@RequestMapping(value = "/getListById", method = RequestMethod.GET)
	@ResponseBody
	public Object getListById(int page, int limit, String classId) {
		if (!classId.equals("undefined")) {        //参数不为undefined
			Map<String, Object> data = new HashMap<>();

			if (Integer.parseInt(classId) == 5) {        //id为5的是爱能人生大类，12.28日改成了查询所有365课程的课时
				List<CourseSection> rows = courseSectionBiz.select_365();
				CourseCatalogue entity = new CourseCatalogue();
				entity.setId(55);
				CourseCatalogue course = baseBiz.selectOne(entity);
				data.put("rows", rows);
				data.put("course", course);
				return new ObjectRestResponse<>().rel(true).data(data);
			} else {        //id不是5

				Example example = new Example(CourseCatalogue.class);
				if (Integer.parseInt(classId) == 1) {    //免费学习的分类id是1，查询所有的免费课程
					example.createCriteria().andEqualTo("isPay", 2);
				} else {
					example.createCriteria().andEqualTo("attr1", Integer.parseInt(classId));
				}
				example.orderBy("id").desc();    //倒序，配合上面的getCourseClassifies（）方法，查找之前的
				PageHelper.startPage(page, limit);
				List<CourseCatalogue> rows = baseBiz.selectByExample(example);
				data.put("rows", rows);
				return new ObjectRestResponse<>().rel(true).data(data);
			}

		} else {    //如果参数为undefind
			return ResponseUtil.fail(40301, "错误！");
		}

	}

	/**
	 * 12.29    根据课程分类id获取分类课程
	 *
	 * @return
	 */
	@RequestMapping(value = "/getInfoById", method = RequestMethod.GET)
	@ResponseBody
	public Object getInfoById(int page, int limit, String classId) {
		if (!classId.equals("undefined")) {        //参数不为undefined
			Example example = new Example(CourseSection.class);
			if (Integer.parseInt(classId) == 1) {        //免费学习的，全部的免费课时
				Page<Object> result = PageHelper.startPage(page, limit);
//				example.createCriteria().andEqualTo("freeTrail", 0).andEqualTo("deleted", 0).andEqualTo("sectionTypeChoices",0).andLessThan("showTime",new Date());
//				example.orderBy("id").desc();
//				courseSectionBiz.selectByExample(example);
				List<CourseSectionVo> list =  courseSectionBiz.selectAllFree(Integer.parseInt(classId));

				list.forEach(CourseSectionVo ->{
					// 获取每一篇文章在redis中的浏览量，存入到数据库中
					String key  = "id_"+CourseSectionVo.getId();
					Long view = redisUtil.size(key);
					if(view>0){
						Long views = view + CourseSectionVo.getPlayTimes();
						CourseSectionVo.setPlayTimes(Math.toIntExact(views));
//					list.add(CourseSection);
					}
				});
				return new TableResultResponse<>(result.getPages(), list);
			} else {        //全部的课程分类，查该分类下的所有课程的免费课时
				Page<Object> result = PageHelper.startPage(page, limit);
				List<CourseSection> lists = 	courseSectionBiz.selectFrees(classId);
				lists.forEach(CourseSection ->{
					// 获取每一篇文章在redis中的浏览量，存入到数据库中
					String key  = "id_"+CourseSection.getId();
					Long view = redisUtil.size(key);
					if(view>0){
						Long views = view + CourseSection.getPlayTimes();
						CourseSection.setPlayTimes(Math.toIntExact(views));
					}
				});

				return new TableResultResponse<>(result.getPages(), lists);
			}

		} else {    //如果参数为undefind
			return ResponseUtil.fail(40301, "错误！");
		}
	}

	/**
	 * 首页--tap栏分页--"全部"下级页面
	 */
	@RequestMapping(value = "/getListByClassId_couId", method = RequestMethod.GET)
	@ResponseBody
	public Object getListByClassId_couId(int page, int limit, String classId, String couId) {
		Example example = new Example(CourseSection.class);
		if (!couId.equals("undefined") && !couId.equals("0")) {        //课程couId不为undefined或者0，则根据课程id查找课时
			Page<Object> result = PageHelper.startPage(page, limit);
			example.createCriteria().andEqualTo("deleted", 0).andEqualTo("couId", Integer.parseInt(couId)).andLessThan("showTime",new Date());
			example.orderBy("sectionOrder").desc();
		  List<CourseSection> list = 	courseSectionBiz.selectByExample(example);
			list.forEach(CourseSection ->{
				// 获取每一篇文章在redis中的浏览量，存入到数据库中
				String key  = "id_"+CourseSection.getId();
				Long view = redisUtil.size(key);
				if(view>0){
					Long views = view + CourseSection.getPlayTimes();
					CourseSection.setPlayTimes(Math.toIntExact(views));
//					list.add(CourseSection);
				}
			});
			return new TableResultResponse<>(result.getPages(), list);
		} else {    //如果couId参数为undefind，则根据classId查找分类下的全部课时
			Page<Object> result = PageHelper.startPage(page, limit);
			List<CourseSection> lists =	courseSectionBiz.get_sectionsByClassId(Integer.parseInt(classId));    //获取某个分类下的所有课时
			lists.forEach(CourseSection ->{
				// 获取每一篇文章在redis中的浏览量，存入到数据库中
				String key  = "id_"+CourseSection.getId();
				Long view = redisUtil.size(key);
				if(view>0){
					Long views = view + CourseSection.getPlayTimes();
					CourseSection.setPlayTimes(Math.toIntExact(views));
//					list.add(CourseSection);
				}
			});

			return new TableResultResponse<>(result.getPages(), lists);
		}
	}


	/**
	 * 二维码扫描
	 */
	@RequestMapping(value = "/codeBycou", method = RequestMethod.GET)
	@ResponseBody
	public Object codeBycou( String couId) {
		if (couId.equals("undefined")) {        //课程couId不为undefined或者0，则根据课程id查找课时
			   //如果couId参数为undefind，则根据classId查找分类下的全部课时
			  //获取某个分类下的所有课时

			return ResponseUtil.fail(-1,"传参错误!");
		}
		return ResponseUtil.ok(courseSectionBiz.codeBycou(Integer.parseInt(couId)));
	}


	/**
	 * 1、收藏   2、点赞
	 */
	@RequestMapping(value = "/like_or_collect", method = RequestMethod.GET)
	@ResponseBody
	public Object like_or_collect(Integer type, String couId, String userId) {
		if (!couId.equals("undefined") && !userId.equals("undefined")) {
			LikeOrCollect entity = new LikeOrCollect();
			entity.setCouId(Integer.parseInt(couId));
			entity.setUserId(Integer.parseInt(userId));
			entity.setModdifyTime(new Date());
			entity.setType(type);
			try {
				if (type == 1) {  	//收藏
					baseBiz.addCollects(Integer.parseInt(couId));
				}else {			//点赞
					baseBiz.addLikes(Integer.parseInt(couId));
				}
				likeOrCollectBiz.insertSelective(entity);
				return new ObjectRestResponse<>().rel(true);
			}catch (RuntimeException e){
				return new ObjectRestResponse<>().rel(false);
			}
		}else {    //如果参数为undefind
			return ResponseUtil.fail(40301, "错误！");
		}
	}

}
